package com.crocodile.game17.filter;

import cn.hutool.core.util.StrUtil;
import com.crocodile.game17.common.AppException;
import com.crocodile.game17.common.AppExceptionMsgEnum;
import com.crocodile.game17.common.LoginUser;
import com.crocodile.game17.mapper.UserMapper;
import com.crocodile.game17.pojo.User;
import com.crocodile.game17.util.JwtUtil;
import com.crocodile.game17.util.JwtUtilN;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class TokenFilter  extends OncePerRequestFilter {


    @Autowired
    private UserMapper userMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");

        String uri = request.getRequestURI();
        if(uri.equals("/gate/logout")){
            filterChain.doFilter(request,response);
            return;
        }

        //放行未携带token 的请求，交由后面拦截器处理
        if (StrUtil.isBlank(token)) {
            filterChain.doFilter(request,response);
            return;
        }
        //解析token
//        Claims claims;
//        try {
//            claims  = JwtUtil.parseJwt(token);
//        } catch (Exception e) {
//            //token无效
//            throw new AppException(AppExceptionMsgEnum.UNAUTHORIZED);
//        }
//        Long userId = Long.valueOf(claims.getSubject());

        //判断token

        String userIdStr = null;
        try {
            userIdStr = JwtUtilN.parseJwt(token);
        } catch (Exception e) {
            throw new AppException(AppExceptionMsgEnum.UNAUTHORIZED);
        }

         Long userId = Long.valueOf(userIdStr);
        User emp = userMapper.getById(userId);
        if (emp == null) {
            //找不到用户
            throw new AppException(AppExceptionMsgEnum.UNAUTHORIZED);
        }
        //封装用户信息
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(emp);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null,null);

        //存储到SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //放行
        filterChain.doFilter(request,response);


    }
}
